package memorphic.samplr.views.itemRenderers
{
	import flash.events.MouseEvent;
	
	import memorphic.samplr.events.PhotoEvent;
	import memorphic.samplr.models.SamplrPhoto;
	
	import mx.controls.CheckBox;
	import mx.controls.Image;
	
	public class EditTileRenderer extends Image
	{
		public var photo:SamplrPhoto;
		
		private var checkBox:CheckBox;
		
		public function EditTileRenderer()
		{
			super();
			width = 100;
			height = 100;
			maintainAspectRatio = true;
			cacheAsBitmap = true;
		}
		
		protected override function createChildren():void
		{
			super.createChildren();
			
			checkBox = new CheckBox();
			checkBox.width = 20;
			checkBox.height = 20;
			checkBox.addEventListener(MouseEvent.CLICK, onSelected);
			addChildAt(checkBox,numChildren);
		}
		
		protected override function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
		{
			super.updateDisplayList(unscaledWidth, unscaledHeight);
			
			checkBox.x = (unscaledWidth - checkBox.width)/2;
			checkBox.y = (unscaledHeight - checkBox.height);
			
			if (checkBox.instanceIndex < numChildren - 1)
			{
				removeChild(checkBox);
				addChildAt(checkBox, numChildren);
			}
		}
		
		protected override function commitProperties():void
		{
			super.commitProperties();
		}
		
		public override function set data(value:Object):void
		{
			if (photo != value)
			{
				photo = SamplrPhoto(value);
				super.data = value;
				source = photo.sourceThumbnail ? photo.sourceThumbnail : photo.flickrURLThumbnail;
				if (checkBox) checkBox.selected = photo.selected;
			}
		}
		
		private function onSelected(evt:MouseEvent):void
		{
			photo.selected = checkBox.selected;
			dispatchEvent(new PhotoEvent(PhotoEvent.PHOTO_SELECT, photo, true));
		}
	}
}